package com.v1.video.view;

import java.util.Random;

import com.v1.video.util.Utils;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.animation.Animator.AnimatorListener;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.RelativeLayout;

public class DanmuEngine implements Runnable {
    private RelativeLayout container;
    private int indexOfQueue;
    private int mScreenWidth;
    private View itemView;
    private ValueAnimator animator;
    
    public DanmuEngine(Context ctx,RelativeLayout container,int position){
    	mScreenWidth = Utils.getScreenWidth(ctx);
    	this.container = container;
    	indexOfQueue = position;
    }
    
    public int getIndexOfQueue(){
    	return indexOfQueue;
    }
    
    public void setItemView(View item){
    	itemView = item;
    }
    
    public View getItemView(){
    	return itemView;
    }
    
	@Override
	public void run() {
		container.addView(itemView);
		itemView.measure(0, 0);
		int measureHeight = itemView.getMeasuredHeight();
		int measureWidth = itemView.getMeasuredWidth();
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, measureHeight);
		itemView.setLayoutParams(params);
		animator = ValueAnimator.ofFloat(mScreenWidth, -measureWidth);
		animator.setInterpolator(new LinearInterpolator());
		Random random = new Random();
		float scale = random.nextFloat();
		animator.setDuration((long) (3000 + (scale * 1500))).start();
		animator.addUpdateListener(new AnimatorUpdateListener() {

			@Override
			public void onAnimationUpdate(ValueAnimator animation) {
				float value = (Float) animation.getAnimatedValue();
				itemView.setX(value);
			}
		});
		animator.addListener(new AnimatorListener() {
			
			@Override
			public void onAnimationStart(Animator animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationRepeat(Animator animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationEnd(Animator animation) {
				container.removeView(itemView);
			}
			
			@Override
			public void onAnimationCancel(Animator animation) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	public boolean isRunning(){
		if(animator == null){
			return false;
		}
		return animator.isRunning();
	}
    
}
